<template>
  <div>
    <el-card style="margin: 20px;">
      <div slot="header" class="clearfix">
        <span>商品介绍</span>
      </div>

      <el-form :model="formData" label-width="100px">
        <el-form-item label="商品编号" prop="goodsSn">
          <el-input v-model="formData.goodsSn"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="专柜价格" prop="counterPrice">
          <el-input v-model.number="formData.counterPrice"></el-input>
        </el-form-item>
        <el-form-item label="当前价格" prop="retailPrice">
          <el-input v-model.number="formData.retailPrice"></el-input>
        </el-form-item>
        <el-form-item label="是否新品" prop="isNew">
          <el-radio v-model="formData.isNew" :label="true">新品</el-radio>
          <el-radio v-model="formData.isNew" :label="false">非新品</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" prop="isHot">
          <el-radio v-model="formData.isHot" :label="false">普通</el-radio>
          <el-radio v-model="formData.isHot" :label="true">热卖</el-radio>
        </el-form-item>
        <el-form-item label="是否在售" prop="isOnSale">
          <el-radio v-model="formData.isOnSale" :label="true">在售</el-radio>
          <el-radio v-model="formData.isOnSale" :label="false">未售</el-radio>
        </el-form-item>
        <el-form-item label="商品图片" prop="picUrl">
          <el-upload
            class="avatar-uploader"
            action="http://192.168.200.251:8888/admin/storage/create"
            :show-file-list="false"
            :on-success="picUrlSuccess"
            :headers="{'Shopping-Admin-Token': token}">
            <img v-if="formData.picUrl" :src="formData.picUrl" style="width: 100px;">
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
              style="width:100px;height: 100px;border-radius: 10px;border: 2px dashed #ddd;line-height: 100px;"
            >
            </i>
          </el-upload>
        </el-form-item>
        <el-form-item label="宣传画廊" prop="gallery">
          <el-upload
            class="avatar-uploader gallery-upload"
            action="http://192.168.200.251:8888/admin/storage/create"
            :show-file-list="false"
            :on-success="gallerySuccess"
            :headers="{'Shopping-Admin-Token': token}">
            <img
              v-for="(item, index) in formData.gallery"
             :src="item" :key="index"
             style="width: 100px;">

            <i
              class="el-icon-plus avatar-uploader-icon"
              style="width:100px;height: 100px;border-radius: 10px;border: 2px dashed #ddd;line-height: 100px;"
            >
            </i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品单位" prop="unit">
          <el-input v-model="formData.unit"></el-input>
        </el-form-item>
        <el-form-item label="关键字" prop="unit">
          <el-tag v-for="(item, index) in tagList" @close="tagClose(index)" closable style="margin-right: 10px;" :key="index">{{item}}</el-tag>
          <el-input v-show="visible" @blur="addTagList" style="width:100px" v-model="tagMsg"></el-input>
          <el-button v-show="!visible" @click="addKeyWord" type="primary">新增</el-button>
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-cascader
            v-model="formData.categoryId"
            :options="categoryOptions">
          </el-cascader>
        </el-form-item>
        <el-form-item label="所属品牌" prop="brandId">
          <el-select v-model="formData.brandId">
            <el-option
              v-for="(item, index) in brandList"
              :label="item.label"
              :value="item.value"
              :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品简介" prop="brief">
          <el-input v-model="formData.brief"></el-input>
        </el-form-item>
        <el-form-item label="商品详细介绍" prop="detail">
          <el-input type="textarea" v-model="formData.detail"></el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品规格的表格 -->
    <el-card style="margin: 20px;">
      <div slot="header" class="clearfix">
        <span>商品规格</span>
      </div>

      <el-button :type="specificationType === 'default' ? 'primary' : ''" @click="changeType('default')">默认规格支持</el-button>
      <el-button :type="specificationType === 'active' ? 'primary' : ''" @click="changeType('active')">多规格支持</el-button>
      <el-button @click="addSpecificatio" v-show="specificationType === 'active'">添加规格</el-button>

      <el-table :data="specificationsTableData">
        <el-table-column label="规格名" prop="specification"></el-table-column>
        <el-table-column label="规格值" prop="value">
          <template slot-scope="scope">
            <el-tag>{{scope.row['value']}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="规格图片" prop="picUrl">
          <template slot-scope="scope">
            <img :src="scope.row['picUrl']" style="width: 50px;" alt="">
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="specificationType === 'active'">
          <template slot-scope="scope">
            <el-button type="danger" @click="deleteSpecification(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 商品库存的表格 -->
    <el-card style="margin: 20px;">
      <div slot="header" class="clearfix">
        <span>商品库存</span>
      </div>

      <el-table :data="productsTableData">
        <el-table-column label="货品规格" prop="specifications">
          <template slot-scope="scope">
            <el-tag v-for="(item, index) in scope.row['specifications']" style="margin-right: 10px;" :key="index">{{item}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="货品售价" prop="price"></el-table-column>
        <el-table-column label="货品数量" prop="number"></el-table-column>
        <el-table-column label="规格图片" prop="url">
          <template slot-scope="scope">
            <img :src="scope.row['url']" style="width: 50px;" alt="">
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="openEditDialog(scope.row)">设置</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 商品参数 -->
    <el-card style="margin: 20px;">
      <div slot="header" class="clearfix">
        <span>商品参数</span>
      </div>

      <el-button type="primary" @click="setAttrVisible = true">添加</el-button>
      <el-table :data="attributeTableData">

        <el-table-column label="商品参数名称" prop="attribute"></el-table-column>
        <el-table-column label="商品参数值" prop="value"></el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="deleteAttr(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-button v-show="!$route.query.id" type="primary" @click="addGoods">上架商品</el-button>
    <el-button v-show="$route.query.id" type="primary" @click="updateGoods">更新商品</el-button>

    <!-- 商品规格的dialog -->
    <el-dialog
      :visible.sync="specificatioVisible"
      width="400"
      title="设置规格">
      <el-form ref="specificationForm" :model="specificatiFormData" label-width="100px">
        <el-form-item label="规格名" prop="specification">
          <el-input v-model="specificatiFormData.specification"></el-input>
        </el-form-item>
        <el-form-item label="规格值" prop="value">
          <el-input v-model="specificatiFormData.value"></el-input>
        </el-form-item>
        <el-form-item label="规格图片" prop="picUrl">
          <el-upload
            class="avatar-uploader"
            action="http://192.168.200.251:8888/admin/storage/create"
            :show-file-list="false"
            :on-success="speciPicUrlSuccess"
            :headers="{'Shopping-Admin-Token': token}">
            <img v-if="specificatiFormData.picUrl" :src="specificatiFormData.picUrl" style="width: 100px;">
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
              style="width:100px;height: 100px;border-radius: 10px;border: 2px dashed #ddd;line-height: 100px;"
            >
            </i>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button>取 消</el-button>
        <el-button type="primary" @click="specificatiConfirm">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 设置货品的dialog -->
    <el-dialog
      :visible.sync="editDialogVisible"
      width="400"
      title="设置货品">
      <el-form ref="editForm" :model="editFormData" label-width="100px">
        <el-form-item label="货品规格列">
            <el-tag v-for="(item, index) in editFormData.specifications" style="margin-right: 10px;" :key="index">{{item}}</el-tag>
        </el-form-item>
        <el-form-item label="货品售价" prop="price">
          <el-input v-model="editFormData.price"></el-input>
        </el-form-item>
        <el-form-item label="货品数量" prop="number">
          <el-input v-model="editFormData.number"></el-input>
        </el-form-item>
        <el-form-item label="货品图片" prop="url">
          <el-upload
            class="avatar-uploader"
            action="http://192.168.200.251:8888/admin/storage/create"
            :show-file-list="false"
            :on-success="urlSuccess"
            :headers="{'Shopping-Admin-Token': token}">
            <img v-if="editFormData.url" :src="editFormData.url" style="width: 100px;">
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
              style="width:100px;height: 100px;border-radius: 10px;border: 2px dashed #ddd;line-height: 100px;"
            >
            </i>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button>取 消</el-button>
        <el-button type="primary" @click="editFormConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设置商品参数的dialog -->
    <el-dialog
      :visible.sync="setAttrVisible"
      width="400"
      title="设置商品参数">
      <el-form ref="attrForm" :model="attrFormData" label-width="100px">
        <el-form-item label="商品参数名称" prop="attribute">
          <el-input v-model="attrFormData.attribute"></el-input>
        </el-form-item>
        <el-form-item label="商品参数值" prop="value">
          <el-input v-model="attrFormData.value"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button>取 消</el-button>
        <el-button type="primary" @click="attrConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
<script>
import axios from 'axios'

export default {
  name: 'shopList',
  componentTitle: '商品上架',
  data () {
    return {
      token: sessionStorage.getItem('Shopping-Admin-Token'),
      tagList: [],
      tagMsg: '',
      visible: false,
      formData: {
        picUrl: '',
        gallery: [],
        categoryId: []
      },
      categoryOptions: [],
      brandList: [],
      specificationsTableData: [
        {specification: '规格', value: '标准', picUrl: ''}
      ],
      // default active
      specificationType: 'default',
      specificatioVisible: false,
      specificatiFormData: {
        picUrl: '',
        specification: '',
        value: ''
      },
      productsTableData: [
        {
          id: 0,
          number: "0",
          price: "0",
          specifications: ['标准'],
          url: ""
        }
      ],
      editDialogVisible: false,
      editFormData: {
        specifications: [],
        url: ''
      },
      attributeTableData: [],
      setAttrVisible: false,
      attrFormData: {}
    }
  },
  mounted () {
    this.getOptions()

    if (this.$route.query.id) {
      this.getDetail()
    }
  },
  methods: {
    getDetail () {
      axios({
        url: 'http://192.168.200.251:8888/admin/goods/detail',
        method: 'get',
        params: {
          id: this.$route.query.id
        },
        headers: {
          'Shopping-Admin-Token': this.token
        }
      }).then(res => {
        this.formData = res.data.data.goods
        this.formData.categoryId = res.data.data.categoryIds
        this.tagList = res.data.data.goods.keywords.split(',')

        // 'lx1,lx2'.split(',')
        this.specificationsTableData = res.data.data.specifications
        this.productsTableData = res.data.data.products
        this.attributeTableData = res.data.data.attributes


        console.log(res)
      })
    },
    changeType (type) {
      this.specificationType = type

      if (type === 'default') {
        this.specificationsTableData = [
          {specification: '规格', value: '标准', picUrl: ''}
        ]
      } else {
        this.specificationsTableData = []
        this.productsTableData = []
      }
    },
    addSpecificatio () {
      this.specificatioVisible = true
    },
    specificatiConfirm () {
      let newObj = Object.assign({}, this.specificatiFormData)
      this.specificationsTableData.push(newObj)

      if (!this.productsTableData.length) {
        this.productsTableData.push(
          {
            id: 0,
            number: "0",
            price: "0",
            specifications: [newObj.value],
            url: ""
          }
        )
      } else {
        this.productsTableData[0].specifications.push(newObj.value)
      }

      this.$refs.specificationForm.resetFields()
      this.specificatioVisible = false
    },
    deleteSpecification (scope) {
      this.specificationsTableData.splice(scope.$index, 1)
    },
    deleteAttr (scope) {
      this.attributeTableData.splice(scope.$index, 1)
    },
    addGoods () {
      axios({
        url: 'http://192.168.200.251:8888/admin/goods/create',
        method: 'post',
        data: {
          attributes: this.attributeTableData,
          goods: {
            ...this.formData,
            // gallery: this.formData.gallery,
            // ['ulr1', 'url2', 'url3']
            categoryId: this.formData.categoryId[1],
            keywords: this.tagList.toString()
          },
          products: this.productsTableData,
          specifications: this.specificationsTableData
        },
        headers: {
          'Shopping-Admin-Token': this.token
        }
      }).then(res => {
        if (res.data.errno === 0) {
          // this.cancel()
          this.$notify.success({title: '添加成功'})

          // this.search()

          this.$router.push({
            path: '/shoppingManage/shopList'
          })
        } else {
          this.$notify.error({title: '添加失败'})
        }
      })
    },
    // 
    updateGoods () {
      axios({
        url: 'http://192.168.200.251:8888/admin/goods/update',
        method: 'post',
        data: {
          attributes: this.attributeTableData,
          goods: {
            ...this.formData,
            // gallery: this.formData.gallery,
            // ['ulr1', 'url2', 'url3']
            categoryId: this.formData.categoryId[1],
            keywords: this.tagList.toString()
          },
          products: this.productsTableData,
          specifications: this.specificationsTableData
        },
        headers: {
          'Shopping-Admin-Token': this.token
        }
      }).then(res => {
        if (res.data.errno === 0) {
          // this.cancel()
          this.$notify.success({title: '更新成功'})

          // this.search()

          this.$router.push({
            path: '/shoppingManage/shopList'
          })
        } else {
          this.$notify.error({title: '更新失败'})
        }
      })
    },
    openEditDialog (row) {
      this.editDialogVisible = true

      this.editFormData = Object.assign({}, row)
      console.log(row)
    },
    editFormConfirm () {
      this.$set(this.productsTableData, 0, Object.assign({}, this.editFormData))

      this.$refs.editForm.resetFields()
      this.editDialogVisible = false
    },
    attrConfirm () {
      this.attributeTableData.push(Object.assign({}, this.attrFormData))

      this.$refs.attrForm.resetFields()
      this.setAttrVisible = false
    },
    addKeyWord () {
      this.visible = true
    },
    addTagList () {
      this.tagList.push(this.tagMsg)

      this.tagMsg = ''
      this.visible = false
    },
    tagClose (index) {
      this.tagList.splice(index, 1)
    },
    // 上传图片成功的回调函数
    picUrlSuccess (res, file) {
      this.formData.picUrl = res.data.url.replace(/localhost:8888/g, '192.168.200.251:8888')
    },
    gallerySuccess (res, file) {
      this.formData.gallery.push(res.data.url.replace(/localhost:8888/g, '192.168.200.251:8888'))
      // this.formData.gallery = res.data.url.replace(/localhost:8888/g, '192.168.200.251:8888')
    },
    speciPicUrlSuccess (res, file) {
      this.specificatiFormData.picUrl = res.data.url.replace(/localhost:8888/g, '192.168.200.251:8888')
    },
    urlSuccess (res, file) {
      this.editFormData.url = res.data.url.replace(/localhost:8888/g, '192.168.200.251:8888')
    },
    getOptions () {
      axios({
        url: 'http://192.168.200.251:8888/admin/goods/catAndBrand',
        method: 'get',
        headers: {
          'Shopping-Admin-Token': this.token
        }
      }).then(res => {
        console.log(res)
        this.categoryOptions = res.data.data.categoryList
        this.brandList = res.data.data.brandList
      })
    }
  }
}
</script>


<style lang="scss" scoped>
.gallery-upload {
  /deep/ div {
    display: flex;
  }
}
</style>